package com.sinovatech.ologger.constants;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author albert
 *
 */
public class Application {

	public static final String WEB_ATTACH_PATH = "web_attach";
	public static final String WEB_ATTACH_WEB = "web_attach_web";
	final static String APPLICATION_PROPERTY_FILENAME = "/ologger.properties";
	private static DefProperties props = null;

	public static Properties getProperties(boolean getNewInstant) {
		if (getNewInstant)
			return getInstance();
		else {
			if (props == null)
				return getProperties(true);
			else
				return props;
		}
	}

	private static Properties getInstance() {
		if (props != null) {
			props.clear();
		}
		props = new DefProperties();
		try {
			InputStream in = Application.class.getResourceAsStream(APPLICATION_PROPERTY_FILENAME);
			props.load(in);
			in.close();
		} catch (IOException e) {
		}
		return props;
	}

	public static void init() {

	}

	/**
	 * @author albert
	 *
	 */
	@SuppressWarnings("serial")
	private static class DefProperties extends Properties {

		@Override
		public String getProperty(String key, String defaultValue) {
			String ss = getProperty(key);
			if (ss != null)
				return ss;
			return super.getProperty(key, defaultValue);
		}

		@Override
		public String getProperty(String key) {
			// logger.info("DefProperties.getProperty("+key+")");
			String raw = super.getProperty(key);
			int left = raw == null ? -1 : raw.indexOf('[');
			if (left == -1)
				return raw;

			int right = raw.indexOf(']', left);
			final String nestedKey = raw.substring(left + 1, right);
			String nestedValue = super.getProperty(nestedKey);

			StringBuffer sb = new StringBuffer(raw).replace(left, right + 1, nestedValue);
			return sb.toString();
		}
	}
}
